<template>
  <div class="main-container">
    <div class="topimg" style="margin-bottom: 20px;">图片识别</div>
    <div class="picture-show">
      <img :src="validImageUrl" alt="暂无数据" />
    </div>
    <div class="topimg2" style="margin-bottom: 20px;">设备演示</div>
    <video src="/src/assets/demo.mp4" class="video-container" autoplay controls loop muted></video>
  </div>
</template>

<script>
import { ref, onMounted, computed } from "vue";
import { fishWeightApi } from "@/api/fishWeight";
import defaultimg from "/src/assets/scale.png";

export default {
  setup() {
    const imageUrl = ref("");
    const imageExists = ref(true);

    const validImageUrl = computed(() => {
      return imageUrl.value && imageExists.value ? imageUrl.value : defaultimg;
    });

    const checkImageExists = (url) => {
      return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => resolve(true);
        img.onerror = () => resolve(false);
        img.src = url;
      });
    };

    const getImage = async () => {
      try {
        const response = await fishWeightApi.getScalePhoto();
        // 直接使用完整的图片URL
        const url = response.data.url;
        const exists = await checkImageExists(url);
        if (exists) {
          imageUrl.value = url;
          imageExists.value = true;
        } else {
          imageExists.value = false;
        }
      } catch (error) {
        console.error("获取图片失败:", error);
        imageExists.value = false;
      }
    };

    onMounted(() => {
      getImage();
    });

    return {
      validImageUrl,
    };
  },
};
</script>

<style scoped>
.main-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
  width: 100%;
  /* background-color: red; */
  position: relative;
}

.picture-show {
  width: 100%;
  height: 370px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  position: relative;
  bottom: 15px;
}
.picture-show img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.topimg{
  font-size: 24px;
  height: 40px;
  background-image: url(@/assets/top.png);
  background-size: cover;
  text-align: center;
  position: relative;
  /* bottom: 163px; */
}
.topimg2{ 
  font-size: 24px;
  height: 40px;
  background-image: url(@/assets/top.png);
  background-size: cover;
  text-align: center;
  position: relative;
  bottom: 15px;
}
.video-container{
  width: 100%;
  height: 500px;
  position: relative;
  bottom: 25px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}
</style>